<template>
  <div class="user-profile">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar"
      title="个人信息"
      left-arrow
      @click-left="$router.back()"
    />

    <input type="file" ref="file" hidden @change="onChange"/>
    <van-cell title="头像" is-link @click="$refs.file.click()">
      <van-image class="avatar"
        round
        fit="cover"
        :src="users.photo"
      />
    </van-cell>
    <van-cell title="昵称" is-link
      :value="users.name"
      @click="isShowEditNickname=true"
    />
    <van-cell title="性别" is-link
      :value="users.gender ?'女' :'男'"
      @click="isShowEditGender=true"
    />
    <van-cell title="生日" is-link
      :value="users.birthday"
      @click="isShowEditBirthday=true"
    />
    <!-- 昵称的弹出层 -->
    <van-popup position="bottom"
      :style="{ height: '100%' }"
      v-model="isShowEditNickname"
    >
      <EditNickname
        v-if="isShowEditNickname"
        v-model="users.name"
        @clickLeft="isShowEditNickname=false"
      />
    </van-popup>
    <!-- 性别的弹出层 -->
    <van-popup position="bottom"
      v-model="isShowEditGender"
    >
      <EditGender
        v-if="isShowEditGender"
        v-model="users.gender"
        @cancel="isShowEditGender=false"
      />
    </van-popup>
    <!-- 生日的弹出层 -->
    <van-popup position="bottom"
      v-model="isShowEditBirthday"
    >
      <EditBirthday
        v-if="isShowEditBirthday"
        v-model="users.birthday"
        @cancel="isShowEditBirthday=false"
      />
    </van-popup>
    <!-- 头像的弹出层 -->
    <van-popup position="bottom"
      :style="{ height: '100%' }"
      v-model="isShowEditAvatar"
    >
      <EditAvatar :img="imgSrc"
        v-if="isShowEditAvatar"
        @cancel="isShowEditAvatar=false"
        @onSuccess="users.photo=$event"
      />
    </van-popup>
  </div>
</template>

<script>
import { getUserProfile } from '@/api/user.js'
import EditNickname from './components/editNickname.vue'
import EditGender from './components/editGender.vue'
import EditBirthday from './components/editBirthday.vue'
import EditAvatar from './components/editAvatar.vue'
export default {
  data () {
    return {
      users: {},
      isShowEditNickname: false,
      isShowEditGender: false,
      isShowEditBirthday: false,
      isShowEditAvatar: false,
      imgSrc: ''
    }
  },

  created () {
    this.loadUserProfile()
  },

  methods: {
    async loadUserProfile () {
      const res = await getUserProfile()
      this.users = res
    },
    onChange (e) {
      this.isShowEditAvatar = true
      const file = e.target.files[0]
      // 将文件对象转成url
      this.imgSrc = URL.createObjectURL(file)
    }
  },
  components: {
    EditNickname,
    EditGender,
    EditBirthday,
    EditAvatar
  }
}
</script>

<style scoped lang='less'>
.user-profile {
  .avatar {
    width: 60px;
    height: 60px;
  }
}
</style>
